﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace Huioo.Learning.WPF.WpfApp
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void OnReadBook(object sender, RoutedEventArgs e)
        {
            // 获取资源
            var info = Application.GetResourceStream(new Uri("Resources/Books.xml", UriKind.Relative));

            var books = XElement.Load(info.Stream);
            var bookList = from book in books.Elements("Book")
                           orderby (string)book.Attribute("Author")
                           select new
                           {
                               Name = (string)book.Attribute("Name"),
                               Author = (string)book.Attribute("Author")
                           };
            foreach (var book in bookList)
                _text.Text += book.ToString() + Environment.NewLine;
        }

        /// <summary>
        /// 资源获取，等同于使用Application.GetResourceStream
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        Stream GetResourceStream(string name)
        {
            string asmName = Assembly.GetExecutingAssembly().GetName().Name;
            var rm = new ResourceManager(asmName + ".g",
                Assembly.GetExecutingAssembly());
            using (var set = rm.GetResourceSet(
               CultureInfo.CurrentCulture, true, true))
            {
                return (Stream)set.GetObject(name, true);
            }
        }
    }
}
